package com.cmge.ad.controller.store;

import com.cmge.ad.controller.BaseController;
import com.cmge.ad.model.*;
import com.cmge.ad.service.ArticleService;
import com.cmge.ad.util.Constant;
import com.cmge.ad.util.Pager;
import com.cmge.ad.util.SuprUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: yang
 * \* Date: 2017-11-24
 * \* Time: 14:36
 * \* Description:
 * \
 */
@Controller
public class StoreController extends BaseController{
    public static final Logger logger = Logger.getLogger(StoreController.class);

    @Autowired
    private ArticleService articleService;

    /**
     * 跳转段子仓库列表
     */
    @RequestMapping("/articleStoreList")
    public String articleStoreList(){
        return "/adCrawl/article/article_store_list";
    }

    /**
     * 跳转段子列表
     */
    @RequestMapping("/articleList")
    public String articleList(){
        return "/adCrawl/article/article_list";
    }

    /**
     * 段子仓库列表
     */
    @RequestMapping("/getArticleStoreList")
    public @ResponseBody
    JsonResult getArticleStoreList(HttpSession session, Pager<ArticleStore> pager, ArticleStore article) throws UnsupportedEncodingException {
        JsonResult result = new JsonResult();
        HashMap<String, Object> paramMap = new HashMap<String,Object>();

        if(!StringUtils.isEmpty(article.getContent())){
            article.setContent(URLDecoder.decode(article.getContent(), "utf-8"));
        }

        paramMap.put("article", article);
        articleService.getArticleStoreList(pager,paramMap);
        result.setData(pager.getRows());
        result.setTotalCount(pager.getTotalCount());
        return result;
    }

    /**
     * 段子列表
     */
    @RequestMapping("/getArticleList")
    public @ResponseBody
    JsonResult getArticleList(HttpServletRequest request, HttpSession session, Pager<Article> pager, Article article) throws UnsupportedEncodingException {
        JsonResult result = new JsonResult();
        HashMap<String, Object> paramMap = new HashMap<String,Object>();

        if(!StringUtils.isEmpty(article.getContent())){
            article.setContent(URLDecoder.decode(article.getContent(), "utf-8"));
        }

        paramMap.put("article", article);
        articleService.getArticleList(pager,paramMap,request);
        result.setData(pager.getRows());
        result.setTotalCount(pager.getTotalCount());
        return result;
    }

    /**
     * 跳转段子详情页面
     */
    @RequestMapping("/getArticleStoreInfoById")
    public String getArticleStoreInfoById(ModelMap map,String id) {
        ArticleStore article = articleService.getArticleStoreInfoById(id);
        // 获取段子的子分类Menu
        List<Menu> menuList = articleService.getArticleChildMenu();

        map.addAttribute("article", article);
        map.addAttribute("menuList", menuList);
        return "/adCrawl/article/article_store_info";
    }

    /**
     * 跳转段子详情页面
     */
    @RequestMapping("/getArticleInfoById")
    public String getArticleInfoById(HttpServletRequest request,ModelMap map,String id) {
        Article article = articleService.getArticleInfoById(id);

        String path = request.getContextPath();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + ":" + request.getServerPort()
                + path;

        if(article.getType() == 2 && !StringUtils.isEmpty(article.getLocationUrl())){
            article.setLocationUrl(basePath+article.getLocationUrl());
        }

        map.addAttribute("article", article);
        return "/adCrawl/article/article_info";
    }

    /**
     * 获取文章的下一个或上一个Id
     */
    @RequestMapping("/getArticleId")
    public @ResponseBody
    JsonResult getArticleId(Article article) throws UnsupportedEncodingException{
        JsonResult result = new JsonResult();

        if(!StringUtils.isEmpty(article.getContent())){
            article.setContent(URLDecoder.decode(article.getContent(), "utf-8"));
        }

        String id = articleService.getArticleId(article);
        result.setData(id);
        return result;
    }

    /**
     * 获取文章的下一个或上一个Id
     */
    @RequestMapping("/getArticleStoreId")
    public @ResponseBody
    JsonResult getArticleStoreId(ArticleStore article) throws UnsupportedEncodingException{
        JsonResult result = new JsonResult();

        if(!StringUtils.isEmpty(article.getContent())){
            article.setContent(URLDecoder.decode(article.getContent(), "utf-8"));
        }

        String id = articleService.getArticleStoreId(article);
        result.setData(id);
        return result;
    }

    @RequestMapping("/getArticleStoreCount")
    public @ResponseBody
    JsonResult getArticleStoreCount(){
        JsonResult result = new JsonResult();
        int count = articleService.getArticleStoreCount();
        result.setData(count);
        return result;
    }

    /**
     * 删除单个仓库段子
     */
    @RequestMapping("/deleteArticleStoreById")
    public @ResponseBody
    Result deleteArticleStoreById(Integer id){
        articleService.deleteArticleStoreById(id);
        return new Result("success", Constant.DEAL_SUCCESS);
    }

    /**
     * 同步仓库段子
     */
    @RequestMapping("/syncArticleStore")
    public @ResponseBody
    Result syncArticleStore(Integer id,Integer menuId,Integer hot){
        if(!articleService.existSyncArticle(id)){
            articleService.syncArticleStore(id,menuId,hot);
            return new Result("success", Constant.DEAL_SUCCESS);
        }else{
            return new Result("fail", Constant.DEAL_FAIL);
        }
    }

    /**
     * 段子菜单列表
     */
    @RequestMapping("/getAllArticleMenu")
    public @ResponseBody
    JsonResult getAllArticleMenu(){
        JsonResult result = new JsonResult();
        List<Menu> menuList = articleService.getAllArticleMenu();

        Menu menu = new Menu();
        menu.setId(-1);
        menu.setMenuName("===请选择===");
        menuList.add(0,menu);

        result.setData(menuList);
        return result;
    }

    /**
     * 跳转到添加段子页面
     */
    @RequestMapping("/addArticle")
    public String addArticle(ModelMap map,Integer gameId) {
        //菜单列表
        List<Menu> menuList = articleService.getAllArticleMenu();
        Menu menu = new Menu();
        menu.setId(-1);
        menu.setMenuName("===请选择===");
        menu.setMenuCode("===请选择===");
        menuList.add(0,menu);
        map.addAttribute("menuList", menuList);

        return "/adCrawl/article/article_add";
    }

    /**
     * 保存段子
     */
    @RequestMapping("/saveArticle")
    public @ResponseBody
    Result saveArticle(Article article){
        try{
            //解决中文乱码问题
            if(!StringUtils.isEmpty(article.getContent())){
                article.setContent(URLDecoder.decode(article.getContent(), "utf-8"));
            }
            //解决中文乱码问题
            if(!StringUtils.isEmpty(article.getAnswer())){
                article.setAnswer(URLDecoder.decode(article.getAnswer(), "utf-8"));
            }
            articleService.saveArticle(article);
            return new Result("success", Constant.DEAL_SUCCESS);
        }catch (Exception e) {
            logger.error("保存段子出错!"+e);
            return new Result("error", Constant.DEAL_FAIL);
        }
    }

    /**
     * 删除段子
     */
    @RequestMapping("/delArticle")
    public @ResponseBody
    Result delArticle(Integer id){
        int count = articleService.delArticle(id);
        if(count == 1){
            return new Result("success", Constant.DEAL_SUCCESS);
        }else{
            return new Result("error", Constant.DEAL_FAIL);
        }
    }

    /**
     * 跳转段子详情页面
     */
    @RequestMapping("/getSyncMenuList")
    public String getSyncMenuList(ModelMap map) {
        // 获取段子的子分类Menu
        List<Menu> menuList = articleService.getArticleChildMenu();

        map.addAttribute("menuList", menuList);
        return "/adCrawl/article/article_store_batchsync";
    }

    /**
     * 批量同步仓库段子
     */
    @RequestMapping("/batchSyncArticleStore")
    public @ResponseBody
    Result batchSyncArticleStore(String ids,Integer menuId){
        String[] id = ids.split(",");
        if(!SuprUtil.isEmptyStringArray(id)){
            for (String syncId : id) {
                articleService.syncArticleStore(Integer.parseInt(syncId),menuId,null);
            }
            return new Result("success", Constant.DEAL_SUCCESS);
        }else{
            return new Result("error", Constant.DEAL_FAIL);
        }
    }
}
